<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Goodform_Controller Extends Controller {

	var $data;

    function Goodform_Controller()
    {
		parent::Controller();
		
		$this->load->helper(array('form', 'url'));
		
		$this->load->library('form_validation');
    }
	
	function view($ID = NULL) {
		if (isset($ID)) {
			if ($this->data['data'] = $this->model->get($ID)) {
				$this->load->view('Goodform/view_table.php', $this->data);
			} else {
				echo 'Record does not exist';
			}
		} else {
			echo 'Error';
		}
	}
	
	function create() {
		$this->_rules();
	
		if ($this->form_validation->run() == FALSE) {
			$this->load->view('Goodform/form_table.php', $this->data);
		} else {
			$input = array();
			foreach ($this->data['items'] as $item) {
				$input[$item['field']] = $this->input->post($item['field']);
			}
			if ($this->model->insert($input)) {
				$s = split("/", uri_string());
				redirect($s[1]);
			} else {
				echo 'Error';
			}
		}
	}
	
	function update($ID = NULL) {
		if (isset($ID)) {
			if ($this->data['data'] = $this->model->get($ID)) {
				$this->_rules();
				
				if ($this->form_validation->run() == FALSE) {
					$this->load->view('Goodform/form_table.php', $this->data);
				} else {
					$input = array();
					foreach ($this->data['items'] as $item) {
						if (strstr($item['display'], 'update')) $input[$item['field']] = $this->input->post($item['field']);
					}
					if ($this->model->update($ID, $input)) {
						$s = split("/", uri_string());
						redirect($s[1]);
					} else {
						echo 'Error';
					}
				}
			} else {
				'Error';
			}
		} else {
			echo 'Error';
		}
	}
	
	function delete($ID = NULL) {
		if (isset($ID)) {
			if (!$this->model->delete($ID)) {
				echo 'Error';
			}
		} else {
			echo 'Error';
		}
	}
	
	function _rules()
	{
		foreach ($this->data['items'] as $item) {
			$this->form_validation->set_rules($item['field'], $item['label'], $item['rules']);
		}
	}
}

?>